package buaa.leetcode.Array;

public class SpiralMatrixII {
	public static int[][] generateMatrix(int n) {
        if (n <= 0) return null;
        if(n == 1){
        	return new int[][]{{1}};
        }
        int m = n;
        int[][] matrix = new int[n][n]; 
        int x = 0, y = 0;
        int count = 1;
   
       while (n > 0) {
    	   if(n==1){
    		   matrix[x][y] = count;
    		   break;
    	   }
           //left to right
           for (int i = 0; i < n - 1; i++) {
               matrix[x][y++] = count++;
           } 
   
           //up to down
           for (int i = 0; i < n - 1; i++) {
        	   matrix[x++][y] = count++;
           }
   
           //right to left
           for (int i = 0; i < n - 1; i++) {
        	   matrix[x][y--] = count++;
           } 
   
           //down to up
           for (int i = 0; i < n - 1; i++) {
        	   matrix[x--][y] = count++;
           }
   
           n = n - 2;
           x++;
           y++;
       }
      /* if(m%2 == 1){
    	   matrix[--x][--y] = count;
       }*/
       return matrix;
   }
	public static void main(String[] args){
		int[][] result = generateMatrix(5);
		for(int i = 0 ; i < 5; i++){
			for(int j = 0 ; j < 5; j++){
				System.out.print("--"+result[i][j]);
			}
			System.out.println();
		}
	}
}
